package com.glb.leetcode;

public class FindSubString {
    public static void main(String[] args) {
        String[] strings = {"babc", "eafbc", "ababc"};
        String result = findLongestCommonSubstring(strings);
        System.out.println("最长公共子串是: " + result);
    }

    public static String findLongestCommonSubstring(String[] strings) {
        if (strings == null || strings.length == 0) {
            return "";
        }

        // 以第一个字符串为基准
        String base = strings[0];
        int maxLength = 0;
        String longestCommonSubstring = "";

        for (int i = 0; i < base.length(); i++) {
            for (int j = i + 1; j <= base.length(); j++) {
                String currentSubstring = base.substring(i, j);
                if (isCommonSubstring(currentSubstring, strings)) {
                    if (currentSubstring.length() > maxLength) {
                        maxLength = currentSubstring.length();
                        longestCommonSubstring = currentSubstring;
                    }
                }
            }
        }

        return longestCommonSubstring;
    }

    public static boolean isCommonSubstring(String substring, String[] strings) {
        for (String string : strings) {
            if (!string.contains(substring)) {
                return false;
            }
        }
        return true;
    }
}

